import { Injectable } from '@nestjs/common';
import { CreateAlbumDto } from './dto/create-album.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { album } from '../../entities/album.entity';
import * as moment from 'moment/moment';
import { v4 as uuidv4 } from 'uuid';
import { AboutAPI, API } from '../../types';
import { Album } from './entities/album.entity';

@Injectable()
export class AlbumService {
  constructor(
    @InjectRepository(album)
    private readonly album: Repository<album>,
  ) {}
  async create(BodyData: CreateAlbumDto) {
    const {
      id,
      title,
      content,
      images,
      show,
      dimension,
      lng,
      lat,
      poiDesc,
      address,
      city,
      district,
      albumTime,
    } = BodyData;
    if (id) {
      console.log(BodyData);
      await this.album.update(
        { id },
        {
          ...BodyData,
          images: images.join(','),
          albumTime: moment(albumTime).valueOf(),
          updateTime: moment().valueOf(),
        },
      );
      return { message: '修改成功' };
    }
    console.log(BodyData);
    await this.album.insert({
      id: uuidv4(),
      title,
      content,
      images: images.join(','),
      show,
      dimension,
      lng,
      lat,
      poiDesc,
      address,
      city,
      district,
      albumTime: moment(albumTime).valueOf(),
      creationTime: moment().valueOf(),
      updateTime: moment().valueOf(),
    });
    return { message: '添加成功' };
  }

  async findAll(query: API.paging & AboutAPI.aboutTableSearch) {
    const { current = 1, pageSize = 15, title = '', show } = query;
    const [users, total] = await this.album.findAndCount({
      skip: (current - 1) * pageSize,
      take: pageSize,
      where: {
        title: Like(`%${title}%`),
        show,
      },
      order: {
        updateTime: 'DESC',
      },
    });
    return {
      list: users.map((el) => {
        return {
          ...el,
          creationTime: moment(Number(el.creationTime)).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
          updateTime: moment(Number(el.updateTime)).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
        };
      }),
      total,
    };
  }

  async findOne(id: string) {
    const data: Album & { images: any; albumTime: any } =
      await this.album.findOne({
        where: { id },
      });
    data.albumTime = moment(Number(data.albumTime)).format(
      'YYYY-MM-DD HH:mm:ss',
    );
    data.images = data.images.split(',');
    return data;
  }

  async remove(id: string) {
    await this.album.delete({ id });
    return { message: '删除成功' };
  }

  async baiduMap(id: string) {
    await this.album.delete({ id });
    return { message: '删除成功' };
  }
}
